﻿using FirstFloor.ModernUI.Windows.Controls;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Vtron.HipcConfigurationTools.VWASStyle
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        #region Fields

        private Point startPosition;
        private Line insertShape;
        private SolidColorBrush color = new SolidColorBrush();
        private double opacity = 1;
        private bool drawFlag = false;
        private Point point;
        private string encodecIp;
        private string decodecIp;
        //ArrayList _commandHistory;
        //int _historyCounter;
        //SerialPort serialPort; 

        #endregion

        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainWindowViewModel();
            //Loaded += MainWindow_Loaded;
        }

        #region Private Helper Methods

        /// <summary>
        /// 退出按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 连接芯片点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenCodecButton_Click(object sender, RoutedEventArgs e)
        {
            Fluent.Button button = sender as Fluent.Button;
            bool result;
            (DataContext as MainWindowViewModel).Init(button.Content.ToString(), out result);
            if (result)
            {
                config_RibbonTabItem.Visibility = Visibility.Visible;
                button.IsDefinitive = true;
            }
            else
            {
                config_RibbonTabItem.Visibility = Visibility.Collapsed;
                button.IsDefinitive = false;
            }
        }

        /// <summary>
        /// 删除芯片点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteCodec_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem menuItem = sender as Fluent.MenuItem;
            (DataContext as MainWindowViewModel).DeleteCodec(menuItem.Tag.ToString());
        }

        private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            drawFlag = true;
            Button button = sender as Button;
            point = button.TranslatePoint(new Point(), connect_Grid);
            startPosition = new Point(button.ActualWidth, button.ActualHeight / 2);
            insertShape = new Line() { Stroke = (color.Color == Brushes.Transparent.Color ? Brushes.Black : color), StrokeThickness = 2 };
            insertShape.Opacity = opacity / 2;
            Canvas.SetLeft(insertShape, startPosition.X + point.X);
            Canvas.SetTop(insertShape, startPosition.Y + point.Y);
            connect_Grid.Children.Add(insertShape);
            encodecIp = button.Content.ToString();
        }

        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            Canvas board = sender as Canvas;
            if (drawFlag && insertShape != null)
            {
                insertShape.X1 = 0;
                insertShape.Y1 = 0;
                insertShape.X2 = e.GetPosition(board).X - startPosition.X - point.X - 1;
                insertShape.Y2 = e.GetPosition(board).Y - startPosition.Y - point.Y - 1;
            }
        }

        private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Button button = sender as Button;
            Point point2 = button.TranslatePoint(new Point(), connect_Grid);
            insertShape.X2 = point2.X - startPosition.X - point.X;
            insertShape.Y2 = point2.Y - startPosition.Y - point.Y + button.ActualHeight / 2;
            drawFlag = false;
            if (insertShape != null)
            {
                insertShape.Opacity = opacity;
            }
            decodecIp = button.Content.ToString();
            if (!string.IsNullOrEmpty(encodecIp))
            {
                if ((DataContext as MainWindowViewModel).EncodedDecodedConnection(encodecIp, decodecIp))
                {
                    insertShape.Tag = encodecIp;
                    MenuItem menuItem = new MenuItem();
                    menuItem.Click += menuItem_Click;
                    menuItem.Header = "断开连接";
                    ContextMenu contextMenu = new ContextMenu();
                    contextMenu.Items.Add(menuItem);
                    insertShape.ContextMenu = contextMenu;
                    encodecIp = String.Empty;
                }
                else
                {
                    connect_Grid.Children.Remove(insertShape);
                    insertShape = null;
                }
            }
        }

        private void menuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            ContextMenu contextMenu = menuItem.Parent as ContextMenu;
            Line line = contextMenu.PlacementTarget as Line;

            if ((DataContext as MainWindowViewModel).EncodedDecodedDisconnection(decodecIp))
            {
                connect_Grid.Children.Remove(line);
            }
        }

        private void connect_Grid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (drawFlag)
            {
                drawFlag = false;
                connect_Grid.Children.Remove(insertShape);
                insertShape = null;
            }
        }

        private void BackstageTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is Fluent.BackstageTabControl)
            {
                (DataContext as MainWindowViewModel).SaveCodecList();
            }
        }

        private void DataGridDeleteButton_Click(object sender, RoutedEventArgs e)
        {
            ModernButton modernButton = sender as ModernButton;
            (DataContext as MainWindowViewModel).DeleteCodec(modernButton.Tag.ToString());
        }

        //void MainWindow_Loaded(object sender, RoutedEventArgs e)
        //{
        //    _commandHistory = new ArrayList();
        //    _historyCounter = 0;
        //    CommandInputBox.PreviewKeyUp += new System.Windows.Input.KeyEventHandler(InputBox_PreviewKeyUp);
        //    CommandInputBox_FocusEvent(CommandInputBox, null);
        //    SerialPortConnect();
        //}

        //void CommandInputBox_FocusEvent(object sender, RoutedEventArgs e)
        //{
        //    if (e != null && e.RoutedEvent.Name == "GotFocus")
        //    {
        //        CommandInputBox.Foreground = Brushes.Black;
        //        CommandInputBox.Text = String.Empty;
        //        CommandInputBox.Items.Clear();
        //    }
        //    else
        //    {
        //        CommandInputBox.Foreground = Brushes.Blue;
        //        CommandInputBox.Text = "在这里键入命令！";
        //        CommandInputBox.Items.Clear();
        //    }
        //}

        //void InputBox_PreviewKeyUp(object sender, KeyEventArgs e)
        //{
        //    string command;
        //    try
        //    {
        //        switch (e.Key)
        //        {
        //            case Key.Return:
        //                command = CommandInputBox.Text;
        //                if (command.Length != 0)
        //                {
        //                    for (int i = 0; i < _commandHistory.Count; i++)
        //                    {
        //                        if (command == (string)_commandHistory[i])
        //                        {
        //                            _commandHistory.RemoveAt(i);
        //                            i = _commandHistory.Count;
        //                        }
        //                    }

        //                    _commandHistory.Insert(0, command);
        //                }
        //                serialPort.WriteLine(command);
        //                CommandInputBox.Text = String.Empty;
        //                break;
        //            case Key.Up:
        //                if (_historyCounter < _commandHistory.Count)
        //                {
        //                    CommandInputBox.Text = _commandHistory[_historyCounter] as string;
        //                    _historyCounter++;
        //                }
        //                break;
        //            case Key.Down:
        //                if (_historyCounter > 0)
        //                {
        //                    _historyCounter--;
        //                    CommandInputBox.Text = _commandHistory[_historyCounter] as string;
        //                }
        //                break;
        //            default:
        //                _historyCounter = 0;
        //                break;
        //        }


        //    }
        //    catch (Exception exception)
        //    {
        //        OnError(exception);
        //    }
        //}

        //private void connect_Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        //{
        //    drawFlag = false;
        //    connect_Grid.Children.Remove(insertShape);
        //    insertShape = null;
        //}

        //private void ConnectionDecodedButton_Click(object sender, RoutedEventArgs e)
        //{
        //    Fluent.Button senderButton = sender as Fluent.Button;
        //    DataContext = new MainWindowViewModel(senderButton.Content.ToString());
        //    SerialPortConnect();
        //}

        //void SerialPortConnect()
        //{
        //    serialPort = new SerialPort();
        //    serialPort.PortName = "COM1";
        //    serialPort.BaudRate = 115200;
        //    serialPort.Parity = Parity.None;
        //    serialPort.DataBits = 8;
        //    serialPort.StopBits = StopBits.One;
        //    serialPort.Handshake = Handshake.None;
        //    serialPort.ReadTimeout = 500;
        //    serialPort.WriteTimeout = 500;
        //    serialPort.DataReceived += DataReceived;
        //    serialPort.Open();
        //}

        //void DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    int numOfByte = serialPort.BytesToRead;
        //    byte[] bytes = new byte[numOfByte];
        //    int count = serialPort.Read(bytes, 0, numOfByte);
        //    string result = Encoding.ASCII.GetString(bytes);

        //    this.Dispatcher.Invoke(new Action(() =>
        //        {
        //            ImmediateWindow.Text += result;
        //            ImmediateWindow.ScrollToEnd();
        //        }));
        //}

        #endregion
    }
}
